<?php

$url = "https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2";
$limit = isset($_GET["limit"])?$_GET["limit"]:10;
$offset = isset($_GET["offset"])?$_GET["offset"]:0;
$begin_date = isset($_GET["begin_date"])?$_GET["begin_date"]:"2019-01-01";
$end_date = isset($_GET["end_date"])?$_GET["end_date"]:"2019-01-30";
$complainted_mchid = isset($_GET["complainted_mchid"])?$_GET["complainted_mchid"]:"";
if($complainted_mchid==""){
    $url = $url."?limit=".$limit."&offset=".$offset."&begin_date=".$begin_date."&end_date=".$end_date;
}else{
    $url = $url."?limit=".$limit."&offset=".$offset."&begin_date=".$begin_date."&end_date=".$end_date."&complainted_mchid=".$complainted_mchid;
}
//获取签名
$sign = getSign($url);

$header = array(
    "Authorization:".$sign,
    "Content-Type:"."application/json;charset='utf-8'",
//    "User-Agent:"."Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2",

);

//echo $sign;
$data = curl_get($url,$header);
$data = json_decode($data);
if($data){
    $d = $data["data"];
    if($d){
        for($i=0;$i<count($d);$i++){
            //获取的是详细信息每一项
            $item = $d[$i];
            //获取里面的单个字段就用 $item[$i]
        }
    }
}

/**
 * http请求
 * @param $url
 * @param int $httpCode
 * @return mixed
 */
function curl_get($url,$header){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_HEADER, 0);//返回response头部信息
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

    //不做证书验证  在linu下部署改为true
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
    curl_setopt($ch,CURLOPT_URL,$url);
    $file_contents = curl_exec($ch);
    //打印请求的header信息

    $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
    curl_close($ch);
    return $file_contents;
}



/**
 * @param $url 签名
 * @return string
 */
function getSign($url){
    $url_parts = parse_url($url);
    $body = "";
    $t = time();
    $s = uuid();
    $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
    $mch_private_key = file_get_contents("wx.key");
    $message = "GET"."\n".
        $canonical_url."\n".
        $t."\n".
        $s."\n".
        $body."\n";

    openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
    $sign = base64_encode($raw_sign);
    $schema = 'WECHATPAY2-SHA256-RSA2048 ';
    $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
        "1607783137",$s, $t, "78359A1764D8D81838CF39F2EB7E0381E536CF2E", $sign);
    return $schema.$token;
}

function  uuid()
{
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr ( $chars, 0, 8 ) . '-'
        . substr ( $chars, 8, 4 ) . '-'
        . substr ( $chars, 12, 4 ) . '-'
        . substr ( $chars, 16, 4 ) . '-'
        . substr ( $chars, 20, 12 );
    return $uuid ;
}